/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package wasolicitudesfiec.authentication;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

/**
 *
 * @author Larry
 */
public class AuthenticationPhaseListener implements PhaseListener {

    private static final String USER_LOGIN_OUTCOME = "login";
    public static final String USER_SESSION_KEY = "user";
    
    public void afterPhase(PhaseEvent event) {
        FacesContext context = event.getFacesContext();

        if (userExists(context)) {
            // allow processing of the requested view
            return;
        } else {
            // send the user to the login view
            if (requestingSecureView(context)) {
                context.responseComplete();
                context.getApplication().
                        getNavigationHandler().handleNavigation(context,null,USER_LOGIN_OUTCOME);
            }
        }
    }

    public void beforePhase(PhaseEvent arg0) {
        //throw new UnsupportedOperationException("Not supported yet.");
    }

    public PhaseId getPhaseId() {
        return PhaseId.RESTORE_VIEW;
    }

    private boolean requestingSecureView(FacesContext context) {
        ExternalContext extContext = context.getExternalContext();       
        String path = extContext.getRequestPathInfo();
        System.out.println("path del request: "+path);
        return (!"/InicioSesion.jsp".equals(path));

    }

    private boolean userExists(FacesContext context) {
        ExternalContext extContext = context.getExternalContext();
        return (extContext.getSessionMap().containsKey(USER_SESSION_KEY));
    }
}
